package com.yznote.cloudesk.file.controller;

import com.yznote.cloudesk.common.Anno.CollectLogs;
import com.yznote.cloudesk.common.constants.ModuleConstant;
import com.yznote.cloudesk.common.constants.YCacheConstant;
import com.yznote.cloudesk.common.oss.OssClientPool;
import com.yznote.cloudesk.common.oss.OssConfig;
import com.yznote.cloudesk.common.pojo.File;
import com.yznote.cloudesk.common.pojo.Personality;
import com.yznote.cloudesk.common.pojo.Result;
import com.yznote.cloudesk.common.tokenShare.YTokenShare;
import com.yznote.cloudesk.common.oss.OssUtils;
import com.yznote.cloudesk.cache.yCache.YCache;
import com.yznote.cloudesk.file.mapper.FileMapper;
import com.yznote.cloudesk.user.mapper.PersonalityMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * oss 内驱图片至html
 */
@Api(tags = "OSS文件系统")
@RestController
@CollectLogs(needResponse = false,moduleName = ModuleConstant.OSS_MODULE)
@RequestMapping("/oss")
@Slf4j
public class OssController {
    @Autowired
    OssClientPool ossClientPool;
    @Autowired
    OssConfig ossConfig;
    @Autowired
    YCache yCache;
    @Autowired
    OssUtils ossUtils;
    @Autowired
    FileMapper fileMapper;
    @Autowired
    YTokenShare yTokenShare;
    @Autowired
    PersonalityMapper personalityMapper;

    @ApiOperation("拉取oss的icons文件")
    @GetMapping(value = "/icons/**", produces = MediaType.ALL_VALUE)
    public byte[] getIcon(HttpServletRequest request) throws IOException {
        //long start = System.currentTimeMillis();
        String requestURL = request.getRequestURI();
        String[] requestURIs = requestURL.split("icons/");
        String ossURL = requestURIs[requestURIs.length - 1];
        byte[] resp;
        if ((resp = yCache.tryGetByteArray(YCacheConstant.PIC,ossURL)) != null) {
            return resp;
        }
        resp = ossUtils.getFileSourceByPath(ossURL);
        yCache.putByteArray(YCacheConstant.PIC,ossURL, resp);
        return resp;
    }

    @ApiOperation("拉取oss头像文件通过url")
    @GetMapping(value = "/heads/**", produces = MediaType.ALL_VALUE)
    public byte[] getUserHeads(HttpServletRequest request) throws IOException {
        //String contentType = request.getContentType();
        //response.setContentType(contentType);
        String requestURL = request.getRequestURI();
        String[] requestURIs = requestURL.split("/");
        Long userId = yTokenShare.get().getUserId();
        String ossURL = "/filesystem/" + userId + "/" + requestURIs[requestURIs.length - 1];
        byte[] resp;
        if ((resp = yCache.tryGetByteArray(YCacheConstant.PIC,ossURL)) != null) {
            return resp;
        }
        resp = ossUtils.getFileSourceByPath(ossURL);
        yCache.putByteArray(YCacheConstant.PIC,ossURL, resp);
        return resp;
    }

    @ApiOperation("根据用户Id获得头像")
    @GetMapping(value = "/getUserHeadsByUserId", produces = MediaType.ALL_VALUE)
    public byte[] getUserHeadsByUserId(@RequestParam Long userId) throws IOException {
        //String contentType = request.getContentType();
        //response.setContentType(contentType);
        Personality personality = personalityMapper.getPersonality(userId);
        String ossURL = personality.getUserHeadsPath();
        byte[] resp;
        if ((resp = yCache.tryGetByteArray(YCacheConstant.PIC,ossURL)) != null) {
            return resp;
        }
        resp = ossUtils.getFileSourceByPath(ossURL);
        yCache.putByteArray(YCacheConstant.PIC,ossURL, resp);
        return resp;
    }

    @ApiOperation("拉取oss文件(一般不使用)")
    @GetMapping("/getFileSource")
    public Result getFileSource(@RequestParam("filePath") String filePath) throws IOException {
        byte[] resp = ossUtils.getFileSourceByPath(filePath);
        // 字节转字符串
        return Result.build(new String(resp, StandardCharsets.UTF_8), 200, "获取文件成功");
    }

    @ApiOperation("根据文件id拉取oss文件")
    @GetMapping("/getFileSourceByFileId")
    public Result getFileSourceByFileId(@RequestParam Long fileId,@RequestParam(value = "encoding",defaultValue = "GBK") String encoding) throws IOException {
        File filemsg = fileMapper.getFilemsg(fileId);
        String filePath = filemsg.getFilePath();
        byte[] resp = null;
        resp = yCache.tryGetByteArray(YCacheConstant.FILE,filePath);
        if (resp == null) {
            resp = ossUtils.getFileSourceByPath(filePath);
            yCache.putByteArray(YCacheConstant.FILE,filePath, resp);
        }
        // 字节转字符串
        return Result.build(new String(resp, encoding), 200, "获取文件成功");
    }

    @ApiOperation("根据文件id拉取oss文件字节数组")
    @GetMapping("/getFileByteArrayByFileId")
    public byte[] getFileByteArrayByFileId(@RequestParam Long fileId) throws IOException {
        File filemsg = fileMapper.getFilemsg(fileId);
        String filePath = filemsg.getFilePath();
        byte[] resp = null;
        resp = yCache.tryGetByteArray(YCacheConstant.FILE,filePath);
        if (resp == null) {
            resp = ossUtils.getFileSourceByPath(filePath);
            yCache.putByteArray(YCacheConstant.FILE,filePath, resp);
        }
        return resp;
    }

    @ApiOperation("根据fileId更新oss文件")
    @PostMapping("/pushFileSource")
    @CollectLogs(needResponse = false,needParam = false,moduleName = ModuleConstant.OSS_MODULE)
    public Result pushFileSource(@RequestBody Map<String, Object> map) throws UnsupportedEncodingException {
        File filemsg = fileMapper.getFilemsg(Long.parseLong(map.get("fileId").toString()));
        String filePath = filemsg.getFilePath();
        String content = map.get("content").toString();
        String decoding = (String)map.get("decoding");
        if(decoding==null||decoding==""){
            decoding = "GBK";
        }
        ossUtils.pushFileSourceWithDecoding(content, filePath,decoding);
        //设置文件更新时间和更新人
        filemsg.setUpdateBy(yTokenShare.get().getUserId());
        filemsg.setUpdateTime(LocalDateTime.now());
        filemsg.setMemory((long) content.getBytes().length);
        fileMapper.updateFileMemory(filemsg);
        // 更新缓存
        yCache.delayDelete(YCacheConstant.FILE,filePath);
        return Result.success(null);
    }

    @ApiOperation("查看用户的使用空间")
    @GetMapping("/getMemory")
    public Result getMemory(){
        return null;
    }
}
